package com.mtr.databoard.domain.screens;

import java.io.IOException;
import java.util.UUID;

public class BackgroundExecuteTask implements Runnable {

    private String sessionId;
    private  UUID screenId;
    private String componentCode;
    private MiddlewareExecutor middlewareExecutor;
    private IMiddlewareMessageSender iMiddlewareMessageSender;
    private long frequency;

    public BackgroundExecuteTask(String sessionId, UUID screenId, String componentCode, MiddlewareExecutor middlewareExecutor, IMiddlewareMessageSender iMiddlewareMessageSender, long frequency) {
        this.sessionId = sessionId;
        this.screenId = screenId;
        this.componentCode = componentCode;
        this.middlewareExecutor = middlewareExecutor;
        this.iMiddlewareMessageSender = iMiddlewareMessageSender;
        this.frequency = frequency;
    }

    @Override
    public void run() {
        while (true)
        {
            var result =middlewareExecutor.execute(sessionId, screenId,componentCode);
            if(result!=null) {
                try {
                    var issend =iMiddlewareMessageSender.send(screenId.toString(),componentCode,result.getData());
                    if(!issend) break;
                    //result.setData(null);
                } catch (IOException e) {
                    e.printStackTrace();
                    break;//发送报错，说明socket 可能断开连接了，可直接退出
                }
            }
            try {
                Thread.sleep(frequency);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
